﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FrameDisplayServer
{

    public class SettingsManager : ISettingsManager
    {
        public string BrowserTargetScreenDeviceName 
        {
            get { return Settings.Default.BrowserTargetScreenDeviceName; }

            set
            {
                Settings.Default.BrowserTargetScreenDeviceName = value;
                Settings.Default.Save();
            }
        }

        public string AccessCode
        {
            get
            {
                string code = Settings.Default.AccessCode;

                if (String.IsNullOrEmpty(code))
                {
                    // Not set yet, so generate a default value.
                    code = this.GenerateRandomAccessCode();
                    this.AccessCode = code;
                }

                return code;
            }

            set
            {
                Settings.Default.AccessCode = value;
                Settings.Default.Save();
            }
        }


        public int Port
        {
            get
            {
                return Settings.Default.Port;
            }

            set
            {
                Settings.Default.Port = value;
                Settings.Default.Save();
            }
        }

        public string BrowserType
        {
            get
            {
                return Settings.Default.BrowserType;
            }

            set
            {
                Settings.Default.BrowserType = value;
                Settings.Default.Save();
            }
        }


        private string GenerateRandomAccessCode()
        {
            StringBuilder sb = new StringBuilder();

            int codeLength = 6;

            Random r = new Random(Environment.TickCount + Guid.NewGuid().GetHashCode());
            for (int co = 0; co < codeLength; co++)
            {
                int value = r.Next(0, (26 + 10) - 1);
                if (value < 26)
                {
                    // A-Z
                    Char letter = (Char)((int)'A' + value);

                    // Favor digit over letter when confusion is possible.
                    if (letter == 'O')
                    {
                        sb.Append('0');
                    }
                    else if (letter == 'I')
                    {
                        sb.Append('1');
                    }
                    else
                    {
                        sb.Append(letter);
                    }
                }
                else
                {
                    // 0-9
                    sb.Append((Char)((int)'0' + (value - 26)));
                }
            }

            return sb.ToString();
        }
    }

}
